package main

import (
	"fmt"
	"go-guide/network/udpv3"
	"net"
)

func main() {

	raddr, err := net.ResolveUDPAddr(udpv3.Network, udpv3.Address)
	if err != nil {
		panic(err)
	}

	udpConn, err := net.DialUDP(udpv3.Network, nil, raddr)

	if err != nil {
		panic(err)
	}
	defer udpConn.Close()

	sendChunk := makeData(10 * 1024)
	recvChunk := make([]byte, 1*1024+10)
	send(err, udpConn, sendChunk, raddr)

	for {
		recvLen, addr, err := udpConn.ReadFromUDP(recvChunk)
		if err != nil {
			panic(err)
		}

		fmt.Printf("recv msg from address: %s, and length: %d\n", addr, recvLen)
	}
}

func send(err error, udpConn *net.UDPConn, sendChunk []byte, raddr *net.UDPAddr) {
	write, err := udpConn.Write(sendChunk)
	if err != nil {
		panic(err)
	}
	fmt.Printf("send msg to address: %s, and length: %d", raddr, write)
}

func makeData(length int) []byte {
	if length < 0 {
		return nil
	}
	return make([]byte, length)
}
